"""
Case Type   : 人为因素
Case Name   : TPCC压力下，DN主所在机器重启
Create At   : 2021/11/19
Owner       : @zou_jialiang0505328126
Description :
    1、利用benchmarksql工具运行TPCC
    2、DN主所在机器重启reboot
    3、重启数据库gs_om -t stop && gs_om -t start
    4、进行dml操作，检查主备一致性
Expect      :
    1、TPCC运行正常
    2、主机重启成功，TPCC正常报错失去连接
    3、数据库重启成功
    4、dml操作成功，主备一致
History     :
"""

import unittest
import time
from datetime import datetime
from yat.test import Node, macro
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class RebootAndRunTPCC(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '---------Opengauss_Reliability_Human_Case007:开始执行---------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.sta1_root_node = Node(node='Standby1Root')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.sta1_dbuser = Node(node='Standby1DbUser')
        self.sta2_dbuser = Node(node='Standby2DbUser')
        self.com = Common()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta_1_sh = CommonSH('Standby1DbUser')
        self.sta_2_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()

    def test_main(self):
        text1 = '----step1: 利用benchmarksql工具运行TPCC expect:TPCC运行正常----'
        self.log.info(text1)
        tpcc_thread = ComThread(
            self.com.startTPCC,
            args=(self.primary_root_node, macro.TPCC_PATH))
        tpcc_thread.setDaemon(True)
        tpcc_thread.start()

        text = '----step2: DN主所在机器重启reboot expect:主机重启成功，TPCC正常报错失去连接----'
        self.log.info(text)
        time.sleep(10)
        result = self.primary_root_node.sh('reboot').result()
        self.log.info(result)

        tpcc_thread.join(int(macro.TPCC_RUN_MAX_TIME) * 2)
        tpcc_result = tpcc_thread.get_result()
        self.log.info(tpcc_result)
        self.assertNotIn(self.constant.TPCC_SUCCESS_MSG, tpcc_result,
                         '执行失败:' + text1)

        text = '----step3: 重启数据库 expect:重启成功----'
        self.log.info(text)
        last_time_cmd = "who -b"
        for i in range(5):
            self.log.info(f'----{i}th check reboot time----')
            time.sleep(180)
            try:
                self.primary_root_node = Node(node='PrimaryRoot')
                last_time_info = \
                    self.primary_root_node.sh(last_time_cmd).result()
            except Exception as e:
                last_time_info = None
                self.log.info(e)
            if last_time_info:
                self.log.info(last_time_info)
                last_time = ' '.join(last_time_info.split()[2:4])
                now_time = datetime.now()
                up_time = now_time - datetime.strptime(
                    last_time, '%Y-%m-%d %H:%M')
                if up_time.total_seconds() < 600:
                    break
        for i in range(1, 65):
            stop_result = self.primary_sh.stopDbCluster()
            self.log.info(stop_result)
            time.sleep(5)
            start_result = self.primary_sh.startDbCluster()
            self.log.info(start_result)
            time.sleep(10)
            result = self.primary_sh.getDbClusterStatus('status')
            if result:
                break
            else:
                time.sleep(60)
        self.assertTrue(result, '执行失败:' + text)

        text = '----step4: 进行dml操作，检查主备一致性 expect:主备一致----'
        self.log.info(text)
        result = self.sta_1_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        result = self.sta_2_sh.check_data_consistency()
        self.assertTrue(result, '执行失败:' + text)
        nodes_tuple = (self.primary_user_node,
                       self.sta1_dbuser, self.sta2_dbuser)
        flag = self.com.check_data_sample_by_all(r'\d', *nodes_tuple)
        self.assertTrue(flag)

        table_dict = self.com.format_sql_result(
            self.primary_sh.executDbSql(r'\d'))
        table_name = table_dict.get('Name')
        for name in table_name:
            select_sql = f'select count(*) from {name};'
            flag = self.com.check_data_sample_by_all(select_sql,
                                                     *nodes_tuple)
            self.assertTrue(flag, '执行失败:' + text)

    def tearDown(self):
        self.log.info("-------------无需清理环境---------------")
        self.log.info(
            '--------Opengauss_Reliability_Human_Case007:执行完成--------')
